// fileSystem  --> fs 文件系统
const fs = require("fs"); //内置
const db = require("../libs/DBHelper");
const jwt = require("jwt-simple");
const md5 = require("md5");

class CartController {
  getGoods(req, res) {
    let strGoods = fs.readFileSync("./data/goods.json");
    let dataGoods = JSON.parse(strGoods);

    res.json({
      msg: "查询成功",
      data: dataGoods,
    });
  }
  getGoodsById(req, res) {
    let { id } = req.query;
    let strGoodsList = fs.readFileSync("./data/goodslist.json");
    let dataGoodsList = JSON.parse(strGoodsList);
    res.json({
      msg: "查询成功",
      data: dataGoodsList.find((item) => item.id == id),
    });
  }
  //加入购物车的接口
  async add(req, res) {
    let { id, name, price, oPrice, number, img, uId } = req.body;
    let sql_query =
      "SELECT * FROM `carts` WHERE `cStatus`=1 AND `uId`=? AND`pId`=?;";
    let params_query = [
      uId, //购买人
      id, //这个id就是pid 产品id
    ];

    let query_result = await db.exec(sql_query, params_query);
    let isAdd = query_result && query_result.length >= 1; //true 已购买

    if (isAdd) {
      //已购买,修改数量和金额
      let sql_update =
        "UPDATE carts SET `cNumber`=cNumber+?,`cTotal`=cNumber*`cPrice` WHERE  `cStatus`=1 AND `uId`=? AND`pId`=?;";
      let params_update = [
        number,
        uId, //购买人
        id, //这个id就是pid 产品id
      ];
      let update_result = await db.exec(sql_update, params_update);
      let isUpdate = update_result && update_result.affectedRows;

      res.json({
        code: isUpdate ? 200 : -200,
        msg: isUpdate ? "加入购物车成功!u" : "加入购物车失败!u",
      });
    } else {
      //插入一条购买记录
      let sql_insert =
        "INSERT INTO carts(`pId`,`uId`,`cName`,`cPrice`,`oPrice`,`cNumber`,`cTotal`,`cImg`)VALUES(?,?,?,?,?,?,?,?);";
      let params_insert = [
        id,
        uId,
        name,
        price,
        oPrice,
        number,
        price * number,
        img,
      ];

      let insert_results = await db.exec(sql_insert, params_insert);

      var isInsert = insert_results && insert_results.affectedRows;

      res.json({
        code: isInsert ? 200 : -200,
        msg: isInsert ? "加入购物车成功!i" : "加入购物车失败!i",
      });
    }
  }

  async getCart(req, res) {
    let { uid } = req.query;
    let sql = "SELECT * FROM `carts`  WHERE `cStatus`=1 AND uId=?;";
    let params = [uid];
    let results = await db.exec(sql, params);
    res.json({
      msg: "查询成功",
      data: results,
    });
  }

  async delete(req, res) {
    let { cId } = req.body;

    let sql = "UPDATE carts SET `cStatus`=0 WHERE `cId`=? ;";
    let params = [cId];

    let results = await db.exec(sql, params);
    let isDel = results && results.affectedRows >= 1;
    res.json({
      code: isDel ? 200 : -200,
      msg: isDel ? "成功成功" : "删除失败",
    });
  }
}

module.exports = new CartController();
